<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import Phaser from 'phaser';

const gameContainer = ref(null);
let game = null;

// 游戏配置
const config = {
  type: Phaser.AUTO,
  width: 400,
  height: 600,
  parent: 'game-container',
  physics: {
    default: 'arcade',
    arcade: {
      gravity: { y: 0 },
      debug: false
    }
  },
  scene: {
    preload: preload,
    create: create,
    update: update
  }
};

// 游戏变量
let player;
let enemies;
let bullets;
let cursors;
let score = 0;
let scoreText;
let gameOver = false;
let level = 1;
let levelText;
let lives = 3;
let livesText;
let spaceKey;
let enemySpawnTime = 0;
let hasSpreadShot = false; // 是否拥有散射弹
let spreadShotTimer = null; // 散射弹计时器
let gameStarted = false; // 控制游戏是否已开始
let selectedShip = 'player1'; // 默认选择player1战机

function preload() {
  // 加载背景图片
  this.load.image('start_bg', '/start.png');
  // 加载玩家飞机图片
  this.load.image('player1', '/player1.png');
  this.load.image('player2', '/player2.png');
  this.load.image('player', '/player1.png'); // 默认使用player1
  // 加载敌机图片
  this.load.image('enemy', '/diji.png');
  // 创建子弹图形
  const bulletGraphics = this.add.graphics();
  
  // 绘制子弹发光效果（淡蓝色）
  bulletGraphics.fillStyle(0x00ffff, 0.5);
  bulletGraphics.fillCircle(0, 0, 12);
  
  // 绘制子弹主体（亮蓝色）
  bulletGraphics.fillStyle(0x00f7ff);
  bulletGraphics.fillRect(-4, -12, 8, 24);
  
  // 生成子弹纹理
  bulletGraphics.generateTexture('bullet', 24, 48);
  bulletGraphics.destroy();
}

let starSprites = [];

function createStars() {
  // 创建星空背景
  const starCount = 200;
  const starColors = [0xffffff, 0xffff00, 0x00ffff, 0xff00ff];

  // 创建星星精灵
  for (let i = 0; i < starCount; i++) {
    const x = Phaser.Math.Between(0, 400);
    const y = Phaser.Math.Between(0, 600);
    const size = Phaser.Math.Between(1, 3);
    const color = starColors[Phaser.Math.Between(0, starColors.length - 1)];
    
    // 创建星星图形
    const starGraphics = this.add.graphics();
    starGraphics.fillStyle(color, Phaser.Math.FloatBetween(0.5, 1));
    starGraphics.fillCircle(0, 0, size);
    
    // 生成纹理
    const key = `star_${i}`;
    starGraphics.generateTexture(key, size * 2, size * 2);
    starGraphics.destroy();
    
    // 创建精灵
    const star = this.add.sprite(x, y, key);
    star.speed = Phaser.Math.FloatBetween(0.3, 1.5) * size; // 速度与大小成正比
    starSprites.push(star);
  }
}

function create() {

  // 添加开始界面背景图
  const background = this.add.image(200, 300, 'start_bg');
  background.setDisplaySize(400, 600);
  background.setOrigin(0.5, 0.5);
  background.setDepth(-1); // 设置背景图层级

  // 创建开始游戏界面
  const titleText = this.add.text(200, 200, '', {
    fontSize: '48px',
    fill: '#fff',
    fontStyle: 'bold'
  }).setOrigin(0.5);

  const startButton = this.add.rectangle(200, 300, 200, 50, 0x00ff00);
  const startText = this.add.text(200, 300, '开始游戏', {
    fontSize: '24px',
    fill: '#000'
  }).setOrigin(0.5);

  // 添加战机选择文本
  this.add.text(200, 360, '选择战机', {
    fontSize: '20px',
    fill: '#fff'
  }).setOrigin(0.5);

  // 添加两个战机选择按钮
  const ship1 = this.add.sprite(150, 420, 'player1').setScale(0.8).setInteractive();
  const ship2 = this.add.sprite(250, 420, 'player2').setScale(0.8).setInteractive();

  // 创建金色边框
  const selectionBox = this.add.rectangle(ship1.x, ship1.y, ship1.width * 1.2, ship1.height * 1.2, 0xffd700);
  selectionBox.setStrokeStyle(2, 0xffd700);
  selectionBox.setFillStyle();

  // 默认选中player1
  selectionBox.setPosition(ship1.x, ship1.y);

  // 添加交互效果
  ship1.on('pointerdown', () => {
    selectedShip = 'player1';
    ship1.clearTint();
    ship2.clearTint();
    selectionBox.setPosition(ship1.x, ship1.y);
    this.load.image('player', '/player1.png');
    this.textures.get('player').setFilter(Phaser.Textures.FilterMode.LINEAR);
  });

  ship2.on('pointerdown', () => {
    selectedShip = 'player2';
    ship1.clearTint();
    ship2.clearTint();
    selectionBox.setPosition(ship2.x, ship2.y);
    this.load.image('player', '/player2.png');
    this.textures.get('player').setFilter(Phaser.Textures.FilterMode.LINEAR);
  });

  // 添加悬停效果
  [ship1, ship2].forEach(ship => {
    ship.on('pointerover', () => {
      if (ship.texture.key !== selectedShip) {
        ship.setAlpha(0.8);
      }
    });
    ship.on('pointerout', () => {
      if (ship.texture.key !== selectedShip) {
        ship.setAlpha(1);
      }
    });
  });

  // 让按钮可交互
  startButton.setInteractive();
  
  // 添加鼠标悬停效果
  startButton.on('pointerover', () => {
    startButton.setFillStyle(0x00dd00);
  });
  
  startButton.on('pointerout', () => {
    startButton.setFillStyle(0x00ff00);
  });

  // 点击开始按钮
  startButton.on('pointerdown', () => {
    gameStarted = true;
    titleText.destroy();
    startButton.destroy();
    startText.destroy();
    
    // 销毁战机选择相关元素和背景图
    background.destroy();
    ship1.destroy();
    ship2.destroy();
    selectionBox.destroy();
    this.children.list.forEach(child => {
      if (child.type === 'Text' && child.text === '选择战机') {
        child.destroy();
      }
    });
    
    // 创建星空背景和游戏元素
    createStars.call(this);
    initGameElements.call(this);
  });

  // 如果游戏已经开始，直接初始化游戏元素
  if (gameStarted) {
    initGameElements.call(this);
  }
}

// 初始化游戏元素的函数
function initGameElements() {
  // 创建玩家飞机（使用选中的战机贴图）
  player = this.physics.add.sprite(200, 500, selectedShip);
  player.setCollideWorldBounds(true);
  player.setScale(0.8);

  // 创建敌机组
  enemies = this.physics.add.group();

  // 创建子弹组
  bullets = this.physics.add.group();

  // 设置键盘控制
  cursors = this.input.keyboard.createCursorKeys();
  spaceKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);

  // 添加碰撞检测
  this.physics.add.collider(bullets, enemies, bulletHitEnemy, null, this);
  this.physics.add.collider(player, enemies, playerHitEnemy, null, this);

  // 添加得分文本，使用更大字体，添加描边和阴影效果
  scoreText = this.add.text(20, 20, '分数: 0', {
    fontSize: '28px',
    fill: '#fff',
    fontStyle: 'bold',
    stroke: '#000',
    strokeThickness: 4,
    shadow: { blur: 4, color: '#000', fill: true }
  });

  levelText = this.add.text(20, 60, '等级: 1', {
    fontSize: '24px',
    fill: '#ffff00',
    fontStyle: 'bold',
    stroke: '#000',
    strokeThickness: 3,
    shadow: { blur: 3, color: '#000', fill: true }
  });

  livesText = this.add.text(20, 95, '生命: 3', {
    fontSize: '24px',
    fill: '#ff0000',
    fontStyle: 'bold',
    stroke: '#000',
    strokeThickness: 3,
    shadow: { blur: 3, color: '#000', fill: true }
  });
}

function update(time) {
  if (!gameStarted || gameOver) {
    return;
  }

  // 更新星星位置
  starSprites.forEach(star => {
    star.y += star.speed;
    if (star.y > 600) {
      star.y = -10;
      star.x = Phaser.Math.Between(0, 400);
    }
  });

  // 玩家控制
  if (cursors.left.isDown && player.x > 0) {
    player.setVelocityX(-200);
  } else if (cursors.right.isDown && player.x < 400) {
    player.setVelocityX(200);
  } else {
    player.setVelocityX(0);
  }

  if (cursors.up.isDown && player.y > 0) {
    player.setVelocityY(-200);
  } else if (cursors.down.isDown && player.y < 600) {
    player.setVelocityY(200);
  } else {
    player.setVelocityY(0);
  }

  // 发射子弹
  if (Phaser.Input.Keyboard.JustDown(spaceKey)) {
    fireBullet();
  }

  // 生成敌机
  if (time > enemySpawnTime) {
    spawnEnemy();
    enemySpawnTime = time + (2000 - level * 100);
    if (enemySpawnTime < 500) enemySpawnTime = 500;
  }

  // 清理超出屏幕的子弹和敌机
  bullets.getChildren().forEach(bullet => {
    if (bullet.y < -10) {
      bullet.destroy();
    }
  });

  enemies.getChildren().forEach(enemy => {
    if (enemy.y > 610) {
      enemy.destroy();
    }
  });
}

function fireBullet() {
  if (hasSpreadShot) {
    // 散射弹：发射3颗子弹，呈扇形分布
    const angles = [-15, 0, 15]; // 子弹发射角度
    angles.forEach(angle => {
      const bullet = bullets.create(player.x, player.y - 20, 'bullet');
      bullet.setScale(0.5);
      // 根据角度计算速度分量
      const speed = 400;
      const radian = Phaser.Math.DegToRad(angle);
      bullet.setVelocity(
        Math.sin(radian) * speed,
        -Math.cos(radian) * speed
      );
    });
    // 散射弹在计时器结束前可以持续使用
  } else {
    // 普通子弹
    const bullet = bullets.create(player.x, player.y - 20, 'bullet');
    bullet.setScale(0.8);
    bullet.setVelocityY(-400);
  }
}

function spawnEnemy() {
  const x = Phaser.Math.Between(30, 370);
  const enemy = enemies.create(x, -20, 'enemy');
  enemy.setScale(0.8);
  enemy.setVelocityY(100 + level * 20);
}

function bulletHitEnemy(bullet, enemy) {
  // 创建爆炸效果
  const explosion = this.add.particles(enemy.x, enemy.y, 'bullet', {
    speed: { min: -150, max: 150 },
    angle: { min: 0, max: 360 },
    scale: { start: 0.8, end: 0 },
    lifespan: 800,
    quantity: 20,
    gravityY: 50,
    on: false
  });

  // 发射一次后自动销毁
  explosion.explode(20);
  this.time.delayedCall(800, () => {
    explosion.destroy();
  });

  bullet.destroy();
  enemy.destroy();

  // 增加分数
  score += 10;
  scoreText.setText('分数: ' + score);

  // 添加分数增加动画效果
  const scorePopup = this.add.text(enemy.x, enemy.y, '+10', {
    fontSize: '24px',
    fill: '#ffff00',
    stroke: '#000000',
    strokeThickness: 4
  }).setOrigin(0.5);

  // 分数文本动画
  this.tweens.add({
    targets: scorePopup,
    y: enemy.y - 50,
    alpha: 0,
    duration: 1000,
    ease: 'Cubic.out',
    onComplete: () => {
      scorePopup.destroy();
    }
  });

  // 屏幕抖动效果
  this.cameras.main.shake(200, 0.005);

  // 随机获得散射弹道具（20%概率）
  if (!hasSpreadShot && Phaser.Math.Between(1, 100) <= 20) {
    hasSpreadShot = true;
    // 显示获得散射弹的提示文本
    const powerupText = this.add.text(player.x, player.y - 50, '获得散射弹! (持续5秒)', {
      fontSize: '20px',
      fill: '#ff0'
    }).setOrigin(0.5);
    
    // 2秒后消失提示文本
    this.time.delayedCall(2000, () => {
      powerupText.destroy();
    });

    // 5秒后移除散射弹效果
    if (spreadShotTimer) {
      this.time.removeEvent(spreadShotTimer);
    }
    spreadShotTimer = this.time.delayedCall(5000, () => {
      hasSpreadShot = false;
      spreadShotTimer = null;
    });
  }

  // 升级
  if (score >= level * 100) {
    level++;
    levelText.setText('等级: ' + level);
  }
}

function playerHitEnemy(player, enemy) {
  enemy.destroy();

  lives--;
  livesText.setText('生命: ' + lives);

  if (lives <= 0) {
    // 创建爆炸效果
    const explosion = this.add.particles(player.x, player.y, 'bullet', {
      speed: { min: -200, max: 200 },
      angle: { min: 0, max: 360 },
      scale: { start: 1, end: 0 },
      lifespan: 1000,
      quantity: 30,
      gravityY: 100,
      on: false
    });

    // 发射一次后自动销毁
    explosion.explode(30);
    this.time.delayedCall(1000, () => {
      explosion.destroy();
    });

    gameOver = true;
    this.physics.pause();
    player.setAlpha(0);

    // 显示游戏结束文本和按钮
    const gameOverText = this.add.text(200, 200, '游戏结束', {
      fontSize: '32px',
      fill: '#fff'
    }).setOrigin(0.5);

    const finalScoreText = this.add.text(200, 250, '最终得分: ' + score, {
      fontSize: '24px',
      fill: '#fff'
    }).setOrigin(0.5);

    // 创建重新开始按钮
    const restartButton = this.add.rectangle(200, 300, 200, 40, 0x00ff00);
    const restartText = this.add.text(200, 300, '重新开始', {
      fontSize: '20px',
      fill: '#000'
    }).setOrigin(0.5);

    // 创建返回主菜单按钮
    const menuButton = this.add.rectangle(200, 360, 200, 40, 0x0000ff);
    const menuText = this.add.text(200, 360, '返回主菜单', {
      fontSize: '20px',
      fill: '#fff'
    }).setOrigin(0.5);

    // 添加按钮交互
    [restartButton, menuButton].forEach(button => {
      button.setInteractive();
      button.on('pointerover', () => button.setAlpha(0.8));
      button.on('pointerout', () => button.setAlpha(1));
    });

    // 重新开始按钮点击事件
    restartButton.on('pointerdown', () => {
      gameOverText.destroy();
      finalScoreText.destroy();
      restartButton.destroy();
      restartText.destroy();
      menuButton.destroy();
      menuText.destroy();
      resetGame.call(this);
    });

    // 返回主菜单按钮点击事件
    menuButton.on('pointerdown', () => {
      gameOverText.destroy();
      finalScoreText.destroy();
      restartButton.destroy();
      restartText.destroy();
      menuButton.destroy();
      menuText.destroy();
      // 清理所有星星精灵
      starSprites.forEach(star => {
        star.destroy();
      });
      starSprites = [];
      resetGame.call(this);
      gameStarted = false;
      this.scene.restart();
    });
  }
}

function resetGame() {
  score = 0;
  level = 1;
  lives = 3;
  gameOver = false;
  hasSpreadShot = false; // 重置散射弹状态
  if (spreadShotTimer) {
    this.time.removeEvent(spreadShotTimer);
    spreadShotTimer = null;
  }

  // 清除所有粒子发射器和特效
  this.game.scene.scenes.forEach(scene => {
    if (scene.particles) {
      scene.particles.emitters.getAll().forEach(emitter => {
        emitter.stop();
        emitter.remove();
      });
      scene.particles.destroy();
    }
  });

  // 清除所有游戏对象
  this.children.list.forEach(child => {
    if (
      (child.type === 'Text' && (child.text.includes('游戏结束') || child.text.includes('点击重新开始'))) ||
      child.type === 'ParticleEmitterManager' ||
      (child.type === 'Sprite' && child.texture.key === 'bullet' && child.scale.x > 1)
    ) {
      child.destroy();
    }
  });

  scoreText.setText('分数: 0');
  levelText.setText('等级: 1');
  livesText.setText('生命: 3');

  player.setAlpha(1);
  player.setPosition(200, 500);
  player.setVisible(true);

  enemies.clear(true, true);
  bullets.clear(true, true);

  this.physics.resume();
}

onMounted(() => {
  game = new Phaser.Game(config);
});

onUnmounted(() => {
  if (game) {
    game.destroy(true);
    game = null;
  }
});
</script>

<template>
  <div class="game-container" ref="gameContainer" id="game-container"></div>
</template>

<style scoped>
.game-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  width: 400px;
  height: 600px;
  border: 2px solid #333;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
</style>